package cn.cellcom.agent.j2ee;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import cn.cellcom.agent.biz.FileLoadBiz;
import cn.cellcom.agent.online.client.AgentClient;
import cn.cellcom.agent.online.client.ClientManager;
import cn.cellcom.agent.online.handler.TraceHandler;
import cn.cellcom.agent.pojo.TUser;
import cn.cellcom.jar.util.LogUtil;

public class SessionListener implements HttpSessionListener {
	public void sessionDestroyed(HttpSessionEvent se) {
		boolean logout = !Thread.currentThread().getName().contains("ContainerBackgroundProcessor");
		LogUtil.i(this.getClass(), "Destroy httpsession " + se.getSession().getId() + " because logout[" + logout + "]");
		HttpSession ss = se.getSession();
		Object object = ss.getAttribute("attribute");
		if (object != null) {
			TUser user = (TUser) object;
			FileLoadBiz.destoryTheQuestionFile(ss, user);
			AgentClient ac = (AgentClient) ClientManager.getInstance().getClient(user.getUsername());
			if (ac != null) {
				/**
				 * 主动退出或者会话超时时client已经不活跃了。这里需要特别说：<br>
				 * 1、主动退出的情况下，必须执行logout<br>
				 * 2、会话超时则需要判断Agentclient是否还活跃，因为如果坐席使用了不同浏览器登陆，则第一个会话时会超时的，此时不应该移除内存的client<br>
				 */
				if (logout) {
					LogUtil.i(this.getClass(), "logout by manual, so call client logout.");
					ac.logout();
				} else {
					if (ac.isActive()) {
						LogUtil.i(this.getClass(), "logout by overdue, but the AgentClient is active, so ingore the session destoryed.");
					} else {
						LogUtil.i(this.getClass(), "logout by overdue, and the AgentClient is dead, so call client logout.");
						ac.logout();
					}
				}
				if (logout || !ac.isActive()) {
				} else {
				}
			}
		}
		TraceHandler.saveTempRecordToMongoDb(null, ss);
	}

	public void sessionCreated(HttpSessionEvent se) {
		LogUtil.i(this.getClass(), "Create httpsession " + se.getSession().getId());
	}
}
